Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Deepest Leaves Sum

Problem Statement

Given a root node of the binary tree, return the sum of all values located at the deepest leaves of a binary tree.

Examples

  • Example 1:
    • Input: root = [1,2,3,4,5,null,7]
Image
  • Expected Output: 16

  • Justification: The deepest level contains the nodes with values 4, 5, and 7, and their sum is 16.

  • Example 2:

    • Input: root = [6,2,8,null,null,7,9,null,null,null,10]
Image
  • Expected Output: 10

  • Justification: The deepest level contains only one node with the value 10, thus the sum is 10.

  • Example 3:

    • Input: root = [1,null,2,null,3,null,4]
Image
  • Expected Output: 4
  • Justification: The binary tree's deepest level has a single node with the value 4. Since it's the only node at that level, the sum is 4.

Solution

To solve this problem, the approach involves a breadth-first search (BFS) traversal of the binary tree. This method is chosen because BFS explores the tree level by level, starting from the root, making it efficient to identify the deepest leaves. By utilizing a queue to keep track of nodes and their levels, we can process each level of the tree sequentially. Once we reach the last level, we calculate the sum of all nodes at that level.

This approach is effective because it ensures that we visit all nodes in the tree while maintaining a clear distinction between different levels. By doing so, we can easily identify when we've reached the deepest level and then sum up the values of the nodes at this level. It is also efficient, as each node is visited exactly once, and no unnecessary computations are done.

Step-by-Step Algorithm

  1. Check for Empty Tree:

    • If the root node is null, return 0 as the tree is empty, and there are no leaves to sum.
  2. Initialize Queue and Variables:

    • Initialize a queue to hold the nodes of the tree along with their level. Start by enqueuing the root node.
    • Initialize levelSum to 0. This variable will hold the sum of the values of the nodes at the current (deepest) level.
  3. Breadth-First Search (BFS) Loop:

    • While the queue is not empty, perform the following steps to process each level of the tree:
      • Note the size of the queue at the start of the loop iteration. This size represents the number of nodes at the current level, as all nodes in the queue are from the same level.
      • Reset levelSum to 0 at the start of processing a new level.
      • Loop through the nodes at the current level (using the noted size of the queue to ensure only nodes of the current level are processed):
        • Dequeue a node from the queue.
        • Add the value of the dequeued node to levelSum.
        • If the dequeued node has a left child, enqueue this child.
        • If the dequeued node has a right child, enqueue this child.
  4. Return Sum of Deepest Leaves:

    • After the loop ends (i.e., the queue is empty, and all levels have been processed), levelSum contains the sum of the values of the nodes at the deepest level of the tree.
    • Return levelSum.

Algorithm Walkthrough

Let's consider the Input: root = [1,2,3,4,5,null,7]

  1. Initialization:

    • The tree is not empty, so we proceed.
    • Queue = [1], levelSum = 0.
  2. First Level Processing (Root Level):

    • Queue size at start = 1 (contains root node 1).
    • levelSum reset to 0.
    • Dequeue 1: Queue = [], levelSum = 1 (value of node 1).
    • Enqueue children of 1: Queue = [2, 3].
  3. Second Level Processing:

    • Queue size at start = 2 (contains nodes 2 and 3).
    • levelSum reset to 0.
    • Dequeue 2: Queue = [3], levelSum = 2 (value of node 2).
    • Enqueue children of 2: Queue = [3, 4, 5].
    • Dequeue 3: Queue = [4, 5], levelSum = 5 (2 + value of node 3).
    • Enqueue right child of 3 (node 7): Queue = [4, 5, 7].
  4. Third Level Processing:

    • Queue size at start = 3 (contains nodes 4, 5, and 7).
    • levelSum reset to 0.
    • Dequeue 4: Queue = [5, 7], levelSum = 4.
    • No children to enqueue.
    • Dequeue 5: Queue = [7], levelSum = 9 (4 + value of node 5).
    • No children to enqueue.
    • Dequeue 7: Queue = [], levelSum = 16 (9 + value of node 7).
    • No children to enqueue.
  5. Return Sum:

    • With the queue empty and all levels processed, the loop ends.
    • levelSum is 16, which is the sum of the values of the nodes at the deepest level.
    • Return 16.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

The time complexity is , where (N) is the number of nodes in the binary tree. This is because each node in the tree is visited exactly once during the BFS traversal.

Space Complexity

The space complexity is , where (W) is the maximum width of the tree. This occurs at the level with the most nodes, which dictates the maximum number of elements that can be stored in the queue at any time. In the worst case, a binary tree could be a complete binary tree, where the last level has nodes, making the space complexity in such scenarios.

Deepest Leaves Sum (medium)
The kth Factor of n (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity